import React, { useState } from "react";
import iconNoSort from "@/assets/image/icon-no-sort.png";
import iconAsc from "@/assets/image/icon-asc.png";
import iconDesc from "@/assets/image/icon-desc.png";
import styles from "./SortBySelector.module.scss";

type GetActiveSortKeyWord = (params: ActiveSortKeyWord) => void

interface SortKeyWordProps {
    name: string,
    type: number,
    active: boolean,
    getActiveSortKeyWord: GetActiveSortKeyWord,
    keyWordGroup?: any
}

export interface ActiveSortKeyWord {
    type: number,
    sortRule: string
}

// 排序关键字ITEM
const SortKeyWord: React.FC<SortKeyWordProps> = (props) => {
    const { name, active, type, getActiveSortKeyWord } = props
    const [sort, setSort] = useState(false)

    const handleSortChange = (type: number) => {
        if (!active) return getActiveSortKeyWord({ type, sortRule: 'desc' })

        const newSort = !sort

        setSort(newSort)
        getActiveSortKeyWord({ type, sortRule: newSort ? 'asc' : 'desc' })
    }

    return <div className={`${styles['key-wrod-block']} ${active ? styles['act-key-wrod-block'] : ''}`} onClick={() => handleSortChange(type)}>
        <span className={styles['key-wrod-name']}>{name}</span>
        {!active ? (<img className={styles['key-wrod-icon']} src={iconNoSort} alt="" />) : null}
        {active ? sort ? (<img className={styles['key-wrod-icon']} src={iconAsc} alt="" />) : (<img className={styles['key-wrod-icon']} src={iconDesc} alt="" />) : null}
    </div>
}

const SortBySelector: React.FC<any> = (props) => {
    const { getSortKeyWord } = props
    const keyWordGroup:any[] = props.keyWordGroup || [
        { name: "销售量", type: 1 },
        { name: "销售额", type: 2 },
        { name: "毛利额", type: 3 },
        { name: "毛利率", type: 4 },
    ]

    const [activeSortKeyWord, setActiveSortKeyWord] = useState<ActiveSortKeyWord>({ type: 1, sortRule: 'asc' })

    const handleActiveSortKeyWordChange = ({ type, sortRule }: ActiveSortKeyWord) => {
        setActiveSortKeyWord(activeSortKeyWord => ({ ...activeSortKeyWord, type, sortRule }))
        getSortKeyWord({ type, sortRule })
    }

    return (<div className={styles["sort-group-wrap"]}>
        {
            keyWordGroup.map(item =>
                (<SortKeyWord key={item.type} name={item.name} type={item.type} active={activeSortKeyWord.type === item.type} getActiveSortKeyWord={handleActiveSortKeyWordChange}></SortKeyWord>)
            )
        }
    </div>);
};

export default SortBySelector;
